<?php

/**
 * This is the model class for table "{{tags}}".
 *
 * The followings are the available columns in table '{{tags}}':
 * @property integer $tag_id
 * @property string $tag_name
 * @property string $tag_time
 * @property integer $news_ids
 *
 * The followings are the available model relations:
 */
class Tags extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @return Tags the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{tags}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('tag_name', 'required'),
			array('tag_name', 'length', 'max'=>255),
			array('tag_time', 'length', 'max'=>50),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('tag_id, tag_name, tag_time, use_num', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'tag_id' => 'Tag',
			'tag_name' => '标签',
			'tag_time' => 'Tag Time',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('tag_id',$this->tag_id);
		$criteria->compare('tag_name',$this->tag_name,true);
		$criteria->compare('tag_time',$this->tag_time,true);
		$criteria->compare('news_ids',$this->news_ids);

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
		));
	}
	
	public function beforeSave(){
		if(parent::beforeSave()){
			if($this->isNewRecord){ //是否最新记录
				$this->tag_time = time();
				//$this->use_num = 1;
			}else{
				//++$this->use_num;
			}
			return true;
		}else{
			return false;
		}
	}
	public function getTagNum($tag_name){
		return 1;
	}
	public static function string2array($tags)
	{
		return preg_split('/ /',trim($tags),-1);
	}

	public static function array2string($tags)
	{
		return implode(' ',$tags);
	}
	public function updateTagUseNum($oldTags, $newTags, $news_id)
	{
		$oldTags=self::string2array($oldTags);
		$newTags=self::string2array($newTags);
		return $this->addTags($newTags,$oldTags,$news_id);
	}
	public function addTags($newTags,$oldTags,$news_id)
	{
		$tbl_tag_news=array();
		//$tags = array_values(array_diff($newTags,$oldTags));
		//$oldTag = array_values(array_diff($newTags,$tags));
		foreach($newTags as $name){
			$isTag = $this->find('tag_name=:name',array(':name'=>$name));
			if($isTag !== null){//存在更新
				$isTag->news_ids = self::arrayToJson($isTag->news_ids,$news_id);
				++$isTag->use_num;
				$isTag->save();
				//$tbl_tag_news[] = $isTag->tag_id;
			}else{//不存在插入
				$newtag_ar = new Tags();
				$newtag_ar->news_ids = $this->getNewsIdsJson($news_id);
				$newtag_ar->use_num = 1;
				$newtag_ar->tag_name = $name;
				$newtag_ar->save();
				//$tbl_tag_news[] = $newtag_ar->primaryKey;
			}
		}
		//return $tbl_tag_news;	
	}
	public static function arrayToJson($news_ids,$news_id){
		$newsTags = json_decode($news_ids,true);
		array_push($newsTags['news_ids'],$news_id);
		return json_encode(array(
			'use_num'=>++$newsTags['use_num'],
			'news_ids'=>array_unique($newsTags['news_ids']),
		));
	}
	public function getNewsIdsJson($news_id){
		return json_encode(array(
			'use_num'=>1,
			'news_ids'=>array($news_id),
		));
	}
	public static function jsonToArray($news_ids){
		return json_decode($news_ids,true);
	}
	public static function getHotTagsOneWeek(){
		//七天内使用率最高的标签
		$sql = "SELECT * FROM `nc_tags` `t` WHERE DATE_FORMAT(FROM_UNIXTIME(`tag_time`),'%Y-%m-%d') > DATE_SUB(CURDATE(),INTERVAL 7 DAY) order by use_num DESC LIMIT 10";
		$res =  Yii::app()->db->createCommand($sql)->queryAll();
		if(!$res){
			$sql = "SELECT * FROM `nc_tags` ORDER BY use_num LIMIT 10";
			return Yii::app()->db->createCommand($sql)->queryAll();
		}
		else
			return $res;
	}
}